package com.xiaotao.service.impl;

import com.xiaotao.entity.Room;
import com.xiaotao.entity.Team;
import com.xiaotao.entity.TeamMember1;
import com.xiaotao.mapper.TeamMapper;
import com.xiaotao.mapper.TeamMemberMapper1;
import com.xiaotao.service.TeamService1;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TeamService1Impl implements TeamService1 {
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private TeamMemberMapper1 teamMemberMapper1;
    @Override
    public ResponseUtil createTeamFromRoom(Room room) {
        if (room == null) {
            return ResponseUtil.get(ResponseEnum.FAIL,"房间信息为空");
        }

        try {
            // 1️ 生成队伍记录
            Team team = new Team();
            team.setRoomId(Integer.valueOf(room.getRoomId()));
            team.setOwnerId(Integer.valueOf(room.getOwnerId()));
            team.setMaxUsers(room.getMaxUsers());
            team.setCreateTime(new Date());
            team.setSuccessTime(new Date());

            teamMapper.insert(team);

            // 2️ 插入成员信息
            List<TeamMember1> members = new ArrayList<>();
            room.getUserMap().forEach((uid, ws) -> {
                TeamMember1 m = new TeamMember1();
                m.setTeamId(team.getId());
                m.setUserId(Integer.valueOf(uid));
                m.setJoinTime(new Date());
                members.add(m);
            });
            teamMemberMapper1.insertBatch(members);// 批量插入
            log.info("组队成功：房间{} → 队伍{}", room.getRoomId(), team.getId());

            //  使用封装响应返回
            return ResponseUtil.get(ResponseEnum.OK, team);
        } catch (Exception e) {
            log.error("创建队伍失败", e);
            return ResponseUtil.get(ResponseEnum.FAIL,"创建队伍失败：" + e.getMessage());
        }
    }

    }

